package org.jeecgframework.web.material.controller;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.xwork.StringUtils;
import org.apache.log4j.Logger;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.ExceptionUtil;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.TemplateExportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.vo.TemplateExcelConstants;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.material.entity.PProductEntity;
import org.jeecgframework.web.material.entity.ProductStoreEntity;
import org.jeecgframework.web.material.service.PProductServiceI;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.jeecgframework.web.system.service.SystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

/**
 * @Description: 产品信息
 * @date 2015-08-19 09:50:46
 * @version V1.0
 * 
 */
@Scope("prototype")
@Controller
@RequestMapping("/pProductController")
public class PProductController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger
			.getLogger(PProductController.class);

	@Autowired
	private PProductServiceI pProductService;
	@Autowired
	private SystemService systemService;
	private String message;

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	/**
	 * 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "pProduct")
	public ModelAndView pProduct(HttpServletRequest request) {
		return new ModelAndView("material/pProduct/pProductList");
	}

	/**
	 * 产品信息新增或更新页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goAddOrUpdate")
	public ModelAndView goAdd(PProductEntity pProduct, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(pProduct.getId())) {
			pProduct = pProductService.getEntity(PProductEntity.class, pProduct
					.getId());
			req.setAttribute("pProductPage", pProduct);
		}
		return new ModelAndView("material/pProduct/pProduct");
	}

	/**
	 * 导入功能跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "upload")
	public ModelAndView upload(HttpServletRequest req) {
		req.setAttribute("controller_name", "pProductController");
		return new ModelAndView("common/upload/pub_excel_upload");
	}

	/**
	 * 
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param user
	 */

	@RequestMapping(params = "datagrid")
	public void datagrid(PProductEntity pProduct, HttpServletRequest request,
			HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(PProductEntity.class, dataGrid);
		// 查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq,
				pProduct, request.getParameterMap());
		try {
			// 自定义追加查询条件
			TSUser user = ResourceUtil.getSessionUserName();
			cq.createAlias("companyId", "companyId");
			cq.eq("companyId.id", user.getCompany().getId());
		} catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		cq.add();
		this.pProductService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * 添加或更新产品信息
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doAddOrUpdate")
	@ResponseBody
	public AjaxJson doAdd(PProductEntity pProduct, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		if (StringUtils.isEmpty(pProduct.getId())) {

			message = "产品信息添加成功";
			try {
				TSUser user = ResourceUtil.getSessionUserName();
				pProduct.setCompanyId(user.getCompany());
				pProductService.save(pProduct);
				// 同时增加库存
				ProductStoreEntity store = new ProductStoreEntity();
				store.setAmount(0);
				store.setCompanyId(user.getCompany());
				store.setProductId(pProduct);
				store.setWarningAmount(0);
				systemService.save(store);

				systemService.addLog(message, Globals.Log_Type_INSERT,
						Globals.Log_Leavel_INFO);
				j.setMsg(message);
			} catch (Exception e) {
				e.printStackTrace();
				message = "产品信息添加失败";
				throw new BusinessException(e.getMessage());
			}
		} else {
			message = "产品信息更新成功";
			PProductEntity t = pProductService.get(PProductEntity.class,
					pProduct.getId());
			try {
				MyBeanUtils.copyBeanNotNull2Bean(pProduct, t);
				pProductService.saveOrUpdate(t);
				systemService.addLog(message, Globals.Log_Type_UPDATE,
						Globals.Log_Leavel_INFO);
			} catch (Exception e) {
				e.printStackTrace();
				message = "产品信息更新失败";
				throw new BusinessException(e.getMessage());
			}
			j.setMsg(message);
		}

		return j;
	}

	/**
	 * 删除产品信息
	 * 
	 * @return
	 */
	@RequestMapping(params = "doDel")
	@ResponseBody
	public AjaxJson doDel(PProductEntity pProduct, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		pProduct = systemService.getEntity(PProductEntity.class, pProduct
				.getId());
		message = "产品信息删除成功";
		try {
			pProductService.delete(pProduct);
			// 同时删除库存
			ProductStoreEntity store = systemService.findUniqueByProperty(
					ProductStoreEntity.class, "productId.id", pProduct.getId());
			if (store != null) {
				systemService.delete(store);
			}

			systemService.addLog(message, Globals.Log_Type_DEL,
					Globals.Log_Leavel_INFO);
		} catch (Exception e) {
			e.printStackTrace();
			message = "产品信息删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 批量删除产品信息
	 * 
	 * @return
	 */
	@RequestMapping(params = "doBatchDel")
	@ResponseBody
	public AjaxJson doBatchDel(String ids, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		message = "产品信息删除成功";
		try {
			for (String id : ids.split(",")) {
				PProductEntity pProduct = systemService.getEntity(
						PProductEntity.class, id);
				pProductService.delete(pProduct);
				// 同时删除库存
				ProductStoreEntity store = systemService.findUniqueByProperty(
						ProductStoreEntity.class, "productId.id", id);
				if (store != null) {
					systemService.delete(store);
				}

				systemService.addLog(message, Globals.Log_Type_DEL,
						Globals.Log_Leavel_INFO);
			}
		} catch (Exception e) {
			e.printStackTrace();
			message = "产品信息删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 导出excel
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXls")
	public String exportXls(PProductEntity pProduct,
			HttpServletRequest request, HttpServletResponse response,
			DataGrid dataGrid, ModelMap modelMap) {
		CriteriaQuery cq = new CriteriaQuery(PProductEntity.class, dataGrid);
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq,
				pProduct, request.getParameterMap());
		TSUser user = ResourceUtil.getSessionUserName();
		cq.createAlias("companyId", "companyId");
		cq.eq("companyId.id", user.getCompany().getId());
		List<PProductEntity> pProducts = this.pProductService
				.getListByCriteriaQuery(cq, false);
		modelMap.put(NormalExcelConstants.FILE_NAME, "产品信息");
		modelMap.put(NormalExcelConstants.CLASS, PProductEntity.class);
		modelMap.put(NormalExcelConstants.PARAMS, new ExportParams("产品信息列表",
				"导出人:" + ResourceUtil.getSessionUserName().getRealName(),
				"导出信息"));
		modelMap.put(NormalExcelConstants.DATA_LIST, pProducts);
		return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}

	/**
	 * 导出excel 使用模板
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXlsByT")
	public String exportXlsByT(PProductEntity pProduct,
			HttpServletRequest request, HttpServletResponse response,
			DataGrid dataGrid, ModelMap modelMap) {
		modelMap.put(TemplateExcelConstants.FILE_NAME, "产品信息");
		modelMap.put(TemplateExcelConstants.PARAMS, new TemplateExportParams(
				"Excel模板地址"));
		modelMap.put(TemplateExcelConstants.MAP_DATA, null);
		modelMap.put(TemplateExcelConstants.CLASS, PProductEntity.class);
		modelMap.put(TemplateExcelConstants.LIST_DATA, null);
		return TemplateExcelConstants.JEECG_TEMPLATE_EXCEL_VIEW;
	}

	/**
	 * 使用excel导入产品信息
	 * 
	 * @param request
	 * @param response
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(params = "importExcel", method = RequestMethod.POST)
	@ResponseBody
	public AjaxJson importExcel(HttpServletRequest request,
			HttpServletResponse response) {
		AjaxJson j = new AjaxJson();

		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<PProductEntity> listPProductEntitys = ExcelImportUtil
						.importExcel(file.getInputStream(),
								PProductEntity.class, params);
				for (PProductEntity pProduct : listPProductEntitys) {
					pProductService.save(pProduct);
				}
				j.setMsg("文件导入成功！");
			} catch (Exception e) {
				j.setMsg("文件导入失败！");
				logger.error(ExceptionUtil.getExceptionMessage(e));
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return j;
	}
}
